package com.miyake.client.datamanage;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DialogBox;
import com.miyake.client.DataService;
import com.miyake.client.datamanage.plugin.MyFilePluginChooser;
import com.miyake.client.tools.ShowDialog;
import com.miyake.client.tools.WaitPopup;

public abstract class ParseFile {

	abstract protected void onParseFinish(String nodeKey);
	private List<String> nodeKeys;

	public ParseFile(List<String> nodeKeys) {
		this.nodeKeys = nodeKeys;
		initialize();
	}

	
	public ParseFile(String nodeKey) {
		this.nodeKeys = new ArrayList<String>();
		nodeKeys.add(nodeKey);
		initialize();
	}
	
	protected void initialize() {
		final MyFilePluginChooser dlg = new MyFilePluginChooser();
		new ShowDialog() {

			@Override
			protected void onOK(String text) {
				setFileParser(dlg.getSelectedKey());
			}

			@Override
			protected DialogBox getDialogBox() {
				return dlg;
			}
			
		};
	}

	private void setFileParser(String selectedKey) {
		WaitPopup.showPopup(nodeKeys.size());
		
		for (final String nodeKey : nodeKeys) {
			DataService.Util.getInstance().setFilePlugin(nodeKey, selectedKey, new AsyncCallback<Void>() {
	
				@Override
				public void onFailure(Throwable caught) {
					Window.alert(caught.getMessage());
				}
	
				@Override
				public void onSuccess(Void result) {
					WaitPopup.hidePopup();
					if (!WaitPopup.isPopupVisible()) {
						onParseFinish(nodeKey);
					}
				}
				
			});
		}
	}
}
